/**
 * @author Steve Sedlmayr
 * @mail ssedlmayr@gmail.com
 * @link http://code.google.com/p/chitin/
 * @version 0.1
 
	The MIT License

	Copyright (c) 2009 Steve Sedlmayr

	Permission is hereby granted, free of charge, to any person obtaining a copy
	of this software and associated documentation files (the "Software"), to deal
	in the Software without restriction, including without limitation the rights
	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
	copies of the Software, and to permit persons to whom the Software is
	furnished to do so, subject to the following conditions:

	The above copyright notice and this permission notice shall be included in
	all copies or substantial portions of the Software.

	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
	THE SOFTWARE.
*/

package srs.chitin.data {
	import flash.events.NetStatusEvent;
	import flash.net.SharedObject;
	import flash.net.SharedObjectFlushStatus;
	import flash.utils.getDefinitionByName;
	import flash.utils.getQualifiedClassName;
	
	public class DiskDataDelegate {
		private static var _classInstance:Class;
		
		public function DiskDataDelegate() {}
		
		/**
		 * Save either all fields excepted or all fields not excepted, based on the value of the 
		 * <code>_filterExceptions</code> flag on <code>DiskDataDelegate._classInstance</code>.
		 * 
		 * @param property The name of the field to which to write.
		 * @param value The value to write to the property.
		 */
		public static function save(property:String, value:*) : void {
			if ( DiskDataDelegate._classInstance == null ) { return; }
			
			var isException:Boolean = false;
			var exceptionIndex:uint = 0;
			
			//Check whether the property is identified in the exception list.
			while ( exceptionIndex < (DiskDataDelegate._classInstance["fieldExceptions"] as Array).length ) {
				if ( property == (DiskDataDelegate._classInstance["fieldExceptions"] as Array)[exceptionIndex] ) {
					isException = true;
					break;
				}
				
				++exceptionIndex;
			}
			
			/* If the isException flag matches the _filterExceptions on DiskDataDelegate._classInstance, 
			   save the value to the SharedObject. */
			if ( isException != (DiskDataDelegate._classInstance["filterExceptions"] as Boolean) ) {
				(DiskDataDelegate._classInstance["getSharedObject"]() as SharedObject).data[property] = value;
			}
		}
		
		/**
		 * Write all data to disk and call back to the invoking object.
		 * 
		 * @param callback The method to defer until writing to disk has completed.
		 * @param scope The invoking object on which to call the callback method.
		 * @param argumentsArray An Array of arguments stored as pass-through back to the callback.
		 */
		public static function writeToDisk() : void {
			if ( DiskDataDelegate._classInstance == null ) { return; }
			
			var flushStatus:String = (DiskDataDelegate._classInstance["getSharedObject"]() as SharedObject).flush(); //Write to disk.
			
			if ( flushStatus != null ) {
                switch (flushStatus) {
					case SharedObjectFlushStatus.PENDING: //We are still writing, so add a listener for the async write operation.
                        (DiskDataDelegate._classInstance["getSharedObject"]() as SharedObject).addEventListener(NetStatusEvent.NET_STATUS, onFlushStatus, false, 0, true);
                        break;
                    case SharedObjectFlushStatus.FLUSHED:
                        callbackFromFlush(); //We are done writing, so invoke the callback.
                        break;
                }
            }
		}
		
		/** 
		 * Removes the flush listener and invokes the callback.
		 * 
		 * @param event A NetStatusEvent that fires natively.
		 */
		public static function onFlushStatus(event:NetStatusEvent) : void {
			(DiskDataDelegate._classInstance["getSharedObject"]() as SharedObject).removeEventListener(NetStatusEvent.NET_STATUS, onFlushStatus, false);
			callbackFromFlush();
		}
		
		/**
		 * Sets the class definition on which DiskDataDelegate will look for properties in a 
		 * subsequent method call on a static method in DiskDataDelegate.
		 * 
		 * @param scope The class definition on which to look for properties.
		 */
		public static function setClassInstance(scope:Class) : void {
			DiskDataDelegate._classInstance = scope;
		}
		
		private static function callbackFromFlush() : void {
			if ( DiskDataDelegate._classInstance["callback"] == null ) { return; }
			if ( DiskDataDelegate._classInstance["scope"] == null ) { return; }
			if ( DiskDataDelegate._classInstance["argumentsArray"] == null ) { return; }
			
			(DiskDataDelegate._classInstance["callback"] as Function).call(DiskDataDelegate._classInstance["scope"], (DiskDataDelegate._classInstance["argumentsArray"] as Array));
		}
	}
}